import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Applayout from '@/layout/Applayout.vue'
import productRoutes from './modules/product'
import orderRoutes from './modules/order'
import settingRoutes from './modules/setting'
import systemRoutes from './modules/system'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { store } from '@/store'
const routes:RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/admin/home'
  },
  {
    path: '/admin',
    component: Applayout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import('../views/home/index.vue'),
        meta: { title: '首页' }
      },
      productRoutes,
      orderRoutes,
      settingRoutes,
      systemRoutes
    ]
  },
  {
    path: '/admin/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  }
]
const router = createRouter({
  history: createWebHashHistory(), // 路由模式 history
  routes // 路由规则
})

router.beforeEach((to, from) => {
  nprogress.start()
  if (to.meta.requiresAuth && !store.state.user) {
    // 页面需要授权但是没有登录，则重写向到登录页
    return {
      path: '/admin/login',
      // 保存当前位置，以便登录后重新跳转到此
      query: { redirect: to.fullPath }
    }
  }
})
router.afterEach(() => {
  nprogress.done()
})
export default router
